package org.theSeed.web.utils;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Servlet工具
 */
public class ServletUtil {
    /**
     * 获取ServletRequestAttributes
     * @return
     */
    public static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

    /**
     * 获取HttpServletRequest
     */
    public static HttpServletRequest getHttpServletRequest(){
        return getServletRequestAttributes().getRequest();
    }

    /**
     * 获取所有请求头
     * @return
     */
    public static Map<String, String> getHeaderMap(){
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = getHttpServletRequest().getHeaderNames();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            String headerValue = getHttpServletRequest().getHeader(headerNames.nextElement());
            headers.put(headerName,headerValue);
        }
        return headers;
    }

    /**
     * 获取所有请求头
     * @return
     */
    public static Map<String, String> getHeaderMap(HttpServletRequest httpServletRequest){
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            String headerValue = httpServletRequest.getHeader(headerNames.nextElement());
            headers.put(headerName,headerValue);
        }
        return headers;
    }

    /**
     * 获取请求头
     * @param headerName
     * @return
     */
    public static String getHeaderValue(String headerName){
        return getHttpServletRequest().getHeader(headerName);
    }

    /**
     * 获取请求头
     * @param headerName
     * @return
     */
    public static String getHeaderValue(HttpServletRequest httpServletRequest,String headerName){
        return httpServletRequest.getHeader(headerName);
    }
}
